/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlinkdemo.fragment;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xuexiang.xaop.annotation.MainThread;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xdlink.component.channel.entity.ConnectStatusEnum;
import com.xuexiang.xdlinkdemo.R;
import com.xuexiang.xdlinkdemo.adapter.ChatMessageAdapter;
import com.xuexiang.xdlinkdemo.device.Constants;
import com.xuexiang.xdlinkdemo.device.provider.ChatServerDataProvider;
import com.xuexiang.xdlinkdemo.device.provider.OnChatListener;
import com.xuexiang.xdlinkdemo.entity.ApiEntity;
import com.xuexiang.xdlinkdemo.entity.ChatMessage;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.NetworkUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;

import static com.xuexiang.xdlinkdemo.device.Constants.ApiType.LOGIN;

/**
 * @author xuexiang
 * @since 2018/9/3 下午8:14
 */
@Page(name = "聊天室服务端")
public class ChatRoomServerFragment extends XPageFragment implements OnChatListener {

    @BindView(R.id.tv_server_status)
    TextView tvServerStatus;
    @BindView(R.id.btn_start_server)
    Button btnStartServer;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.et_send_content)
    EditText etSendContent;
    @BindView(R.id.tv_server_address)
    TextView tvServerAddress;

    private ChatServerDataProvider mChatServer;

    private ChatMessageAdapter mChatAdapter;

    private boolean mIsConnected;
    private boolean mIsLogin;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chat_server;
    }

    @Override
    protected void initViews() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(mChatAdapter = new ChatMessageAdapter());
        recyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    protected void initListeners() {
        mChatServer = new ChatServerDataProvider(getContext());
        mChatServer.setOnChatListener(this);
    }

    @SingleClick
    @OnClick({R.id.btn_start_server, R.id.btn_clear, R.id.btn_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start_server:
                btnStartServer.setEnabled(false);
                mChatServer.startServer();
                break;
            case R.id.btn_clear:
                mChatAdapter.clear();
                mChatAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_send:
                if (!mIsConnected) {
                    ToastUtils.toast("请先启动服务器！");
                    return;
                }
                if (!mIsLogin) {
                    ToastUtils.toast("当前无设备登录！");
                    return;
                }

                String content = etSendContent.getText().toString();
                if (StringUtils.isEmpty(content)) {
                    ToastUtils.toast("发送内容不能为空！");
                    return;
                }

                boolean result = mChatServer.send(new ApiEntity<ChatMessage>(Constants.ApiType.SEND_MESSAGE)
                        .setData(new ChatMessage().setLoginName("服务器")
                                .setContent(content)));
                if (result) {
                    etSendContent.setText("");
                }
                break;
        }
    }

    @Override
    @MainThread
    public void onChatStatusChanged(ConnectStatusEnum status) {
        switch(status) {
            case CONNECT_SUCCESS:
                tvServerAddress.setText(String.format("服务器地址:%s", NetworkUtils.getIPAddress(true)));
                tvServerStatus.setText("已开启");
                tvServerAddress.setVisibility(View.VISIBLE);
                mIsConnected = true;
                break;
            case CONNECT_FAILED:
                btnStartServer.setEnabled(true);
                tvServerAddress.setText("");
                tvServerStatus.setText("已关闭");
                tvServerAddress.setVisibility(View.GONE);
                mIsConnected = false;
                break;
            default:
                break;
        }
    }

    @Override
    @MainThread
    public void onUpdateEvent(String eventType, Object object) {
        switch(eventType) {
            case LOGIN:
                if ((boolean)object) {
                    mIsLogin = true;
                    tvServerStatus.setText("已有设备登录");
                } else {
                    mIsLogin = false;
                }
                break;
            default:
                break;
        }
    }

    @Override
    @MainThread
    public void onUpdateChatMessage(ChatMessage message) {
        mChatAdapter.load(message);
    }

    @Override
    public void onDestroyView() {
        if (mChatServer != null) {
            mChatServer.stopServer();
        }
        super.onDestroyView();
    }
}
